from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.api import namespace_manager
from google.appengine.ext.db.metadata import Namespace

import datetime, logging, hashlib

class Message(db.Model):
    subject = db.StringProperty()
    sender = db.StringProperty()
    category = db.StringProperty()
    atag = db.StringProperty()
    tag = db.StringProperty()
    name = db.StringProperty()
    body = db.TextProperty()
    place = db.StringProperty()
    month = db.StringProperty()
    date = db.DateTimeProperty()
    amount = db.FloatProperty()
    parsed = db.BooleanProperty()
    parent_id = db.IntegerProperty()
    refnum = db.StringProperty()

class AtagStatistics(db.Model):
    atag = db.StringProperty()
    amount = db.FloatProperty()
    updated = db.DateTimeProperty()

def get_hash(user):
    h = ''
    if user.find('@') < 0:
        h = user + '-at-gmail.com'
    else:
        h = user.replace('@', '-at-')
    return hashlib.md5(h).hexdigest()

def ns_set():
    user = users.get_current_user().nickname()
    if user == 'ludmila.voilokova':
        user = 'voilokov'
    namespace_manager.set_namespace(get_hash(user))

def ns_set_admin():
    user = 'voilokov'
    namespace_manager.set_namespace(get_hash(user))

def ns_get_all():    
    list = db.GqlQuery("SELECT * FROM __namespace__")
    return list

def msg_get_all():
    list = Message.all()
    return list

def msg_get_by_ns(ns):
    namespace_manager.set_namespace(ns)
    list = Message.all()
    return list

def msg_clone(item):
    msg = Message(subject = item.subject, date = item.date, sender = item.sender,
                  parsed = False, parent_id = item.key().id())
    return msg

def msg_update_from(msg, record):
    msg.parsed, msg.name, msg.amount, msg.place, msg.atag, msg.date, msg.month, msg.refnum = record
    msg.put()

def msg_get_unparsed():
    list = db.GqlQuery("select * from Message where parsed = False order by date")
    return list

def msg_delete(id):
    logging.info('delete: %d' % id)
    m = Message.get_by_id(id)
    m.delete()

def msg_get(id):
    msg = Message.get_by_id(id)
    return msg

def msg_set_category(id, cat):
    msg = Message.get_by_id(id)
    msg.atag = cat
    msg.parsed = True
    msg.put()
    stat_update(msg)
 
def msg_reset_parsed():
    list = db.GqlQuery("select * from Message where parsed = True order by date")
    for item in list.fetch(100):
        item.parsed = False
        item.put()
    
def stat_get_all():
    list = AtagStatistics.all()
    return list

def stat_reset():
    q = AtagStatistics.all()
    for item in q:
        item.amount = 0.0
        item.put()

def stat_update(item):
    if item.atag is None or len(item.atag) == 0 or item.amount is None:
        return
    kwargs = { 'atag': item.atag, 'amount': 0.0 }
    st = AtagStatistics.get_or_insert(item.atag, **kwargs)
    if st.amount is None:
        st.amount = item.amount
    else:
        st.amount += item.amount
    st.updated = datetime.datetime.now()
    st.put()
    kwargs = { 'atag': 'total', 'amount': 0.0 }
    st = AtagStatistics.get_or_insert('total', **kwargs)
    if st.amount is None:
        st.amount = item.amount
    else:
        st.amount += item.amount
    st.updated = datetime.datetime.now()
    st.put()

def stat_recalc(atag):
    q = msg_get_all()
    q.filter('atag =', atag)
    
    amount = 0.0
    for item in q:
        if item.atag == atag:
            amount += item.amount

    kwargs = { 'atag': atag, 'amount': 0.0 }
    st = AtagStatistics.get_or_insert(atag, **kwargs)
    st.amount = amount
    st.updated = datetime.datetime.now()
    st.put()
    logging.info('atag: %s, amount1: %f' % (atag, amount))
    amount = 0.0
    q = stat_get_all()
    for item in q:
        if item.atag != 'total' and item.atag != 'chase':
            amount += item.amount

    kwargs = { 'atag': 'total', 'amount': 0.0 }
    st = AtagStatistics.get_or_insert('total', **kwargs)
    st.amount = amount
    st.updated = datetime.datetime.now()
    st.put()
    logging.info('amount2: %f' % amount)

